/*
 * @Author: huangtianyang 916072572@qq.com
 * @Date: 2023-11-20 15:02:27
 * @LastEditors: huangtianyang
 * @LastEditTime: 2024-05-14 10:27:08
 * @FilePath: \driving-training-admin\src\views\drivingSchoolManagement\drivingSchool\edit\index.ts
 */
import { PropsFormpData, fileListProps, fileProps, formDataInterface, tagProps } from '@/utils/interface'
import { reactive, ref } from 'vue'
import { listConfig } from './formConfig'
import {
    describeInterface,
    drivingSchoolAdd,
    drivingSchoolDetailed,
    drivingSchoolEdit,
    drivingSchoolOperationInterface,
    passRateInfosInterface
} from '@/apis/drivingSchool'
import { useRoute } from 'vue-router'
import { routerStore } from '@/store/router.store'
import { ElMessage } from 'element-plus'
import router from '@/router'
import { storage } from '@/store/sessionStorage'
import { codeToText } from 'element-china-area-data'
import { addDisplayBlockToImages } from '@/utils'
import { userStore } from '@/store/user.store'
export default class DrivingSchoolOperation {
    formData = reactive<PropsFormpData[]>([...listConfig])
    //编辑类型 create | edit | look
    operation = reactive({
        type: 'create',
        id: '',
        cityPassId: '',
        schoolId: ''
    })
    routerStore = routerStore()
    dialog = reactive({
        title: '编辑风格',
        visible: false,
        width: '70%',
        styleInfo: {
            homeBanner: '',
            theme: ''
        }
    })
    uStore = userStore()
    constructor() {
        const route = useRoute()
        this.operation.type = route.query.type as string
        this.operation.id = route.query?.id as string
        if (this.operation.type === 'create') {
            //初始化数据
            this.formData.forEach((child: PropsFormpData) => {
                if (Object.prototype.toString.call(child) === '[object Array]') {
                    const childList = child as formDataInterface[]
                    childList.forEach((item: formDataInterface) => {
                        if (item.key === 'introduction') {
                            //0'政府资质',1'发展历程', 2'所获荣誉', 3'驾校详情'

                            item.content = []
                            item.value = '政府资质'
                            item.index = 0
                        }
                    })
                }
            })
        } else {
            this.getData()
        }
    }
    getData = (arg?: any) => {
        drivingSchoolDetailed(this.operation.id).then((res: any) => {
            if (Number(res.data.code) === 200) {
                const result = res.data.result
                this.dialog.styleInfo = JSON.parse(res.data.result.styleInfo)
                this.formData.forEach((child: PropsFormpData) => {
                    if (Object.prototype.toString.call(child) === '[object Array]') {
                        const childList = child as formDataInterface[]
                        childList.forEach((item: formDataInterface) => {
                            if (item.key === 'introduction') {
                                //0'政府资质',1'发展历程', 2'所获荣誉', 3'驾校详情'

                                //描述
                                const describeArray: string[] = [
                                    result.governmentQualification[0].tag,
                                    result.developHistory[0].tag,
                                    result.honor[0].tag,
                                    ''
                                ]
                                item.describe = describeArray

                                //内容
                                const contentArray: string[] = [
                                    result.governmentQualification[0].msg,
                                    result.developHistory[0].msg,
                                    result.honor[0].msg,
                                    result.details
                                ]
                                item.content = contentArray
                                item.value = '政府资质'
                                item.index = 0
                            } else if (item.key === 'customerServiceTel') {
                                item.value = result.customerServiceTel
                            } else if (item.key === 'customerServiceUrl') {
                                item.value = result.customerServiceUrl
                            } else if (item.key === 'cityId') {
                                //城市
                                const cityId: any[] = result.cityId?.split('/')
                                const cityName: any[] = result.city?.split('/')
                                item.value = [
                                    { label: cityName[0], id: cityId[0] },
                                    { label: cityName[1], id: cityId[1] }
                                ]
                            } else if (item.key === 'month') {
                                //月份
                                if (result.schoolPassRateInfo.length) {
                                    const recordDate = result.schoolPassRateInfo[0].recordDate + ''
                                    item.value = recordDate.slice(0, 4) + '-' + recordDate.slice(4, 6)
                                }
                            } else if (item.key === 'city_totalPassRate') {
                                //全市通过率
                                if (result.schoolPassRateInfo.length) {
                                    item.value = result.schoolPassRateInfo[0].totalPassRate
                                    this.operation.cityPassId = result.schoolPassRateInfo[0].id
                                    this.operation.schoolId = result.schoolPassRateInfo[1].id
                                }
                            } else if (item.key === 'city_subjectOnePassRate' && result.schoolPassRateInfo.length) {
                                //全市科目一通过率
                                item.value = result.schoolPassRateInfo[0].subjectOnePassRate
                            } else if (
                                item.key === 'city_subjectTwoTotalPassRate' &&
                                result.schoolPassRateInfo.length
                            ) {
                                //全市科目二通过率
                                item.value = result.schoolPassRateInfo[0].subjectTwoTotalPassRate
                            } else if (
                                item.key === 'city_subjectThreeTotalPassRate' &&
                                result.schoolPassRateInfo.length
                            ) {
                                //全市科目三通过率
                                item.value = result.schoolPassRateInfo[0].subjectThreeTotalPassRate
                            } else if (
                                item.key === 'city_subjectFourTotalPassRate' &&
                                result.schoolPassRateInfo.length
                            ) {
                                //全市科目四通过率
                                item.value = result.schoolPassRateInfo[0].subjectFourTotalPassRate
                            } else if (item.key === 'ranking' && result.schoolPassRateInfo.length) {
                                //驾校排名
                                item.value = result.schoolPassRateInfo[1].dateRank
                            } else if (item.key === 'totalPassRate' && result.schoolPassRateInfo.length) {
                                //驾校通过率
                                item.value = result.schoolPassRateInfo[1].totalPassRate
                            } else if (item.key === 'subjectOnePassRate' && result.schoolPassRateInfo.length) {
                                //驾校科目一通过率
                                item.value = result.schoolPassRateInfo[1].subjectOnePassRate
                            } else if (item.key === 'subjectTwoTotalPassRate' && result.schoolPassRateInfo.length) {
                                //驾校科目二通过率
                                item.value = result.schoolPassRateInfo[1].subjectTwoTotalPassRate
                            } else if (item.key === 'subjectThreeTotalPassRate' && result.schoolPassRateInfo.length) {
                                //驾校科目三通过率
                                item.value = result.schoolPassRateInfo[1].subjectThreeTotalPassRate
                            } else if (item.key === 'subjectFourTotalPassRate' && result.schoolPassRateInfo.length) {
                                //驾校科目四通过率
                                item.value = result.schoolPassRateInfo[1].subjectFourTotalPassRate
                            } else if (item.key === 'logo' || item.key === 'homeLogo' || item.key === 'loginLogo') {
                                // else if (item.key === 'homeLogo') {
                                //     item.value = item.value as string
                                // } else if (item.key === 'loginLogo') {
                                //     item.value = item.value as string
                                // }
                                //logo
                                item.value = [
                                    {
                                        index: 0,
                                        tag: '',
                                        type: 'image',
                                        list: [
                                            {
                                                key: result[item.key],
                                                name: ''
                                            }
                                        ]
                                    }
                                ]
                            } else if (item.key === 'qualificationPic') {
                                //驾校资质图
                                const imageArray: fileProps[] = []
                                result.qualificationPic.forEach((f: any, index: number) => {
                                    imageArray.push({
                                        index,
                                        tag: f.tag,
                                        type: 'image',
                                        list: [
                                            {
                                                key: f.pic,
                                                name: f.tag
                                            }
                                        ]
                                    })
                                })
                                item.value = [...imageArray]
                            } else if (item.key === 'schoolVideo') {
                                //驾校视频及展示图
                                const imageArray: fileProps[] = []
                                const videoArray: fileProps[] = [
                                    {
                                        index: Number(item.imageCount),
                                        tag: '',
                                        type: 'video',
                                        list: []
                                    }
                                ]

                                result.schoolPic.forEach((f: any, index: number) => {
                                    imageArray.push({
                                        index,
                                        tag: f.tag,
                                        type: 'image',
                                        list: [
                                            {
                                                key: f.pic,
                                                name: f.tag
                                            }
                                        ]
                                    })
                                })
                                result.schoolVideo.forEach((f: any, index: number) => {
                                    if (f.cover) {
                                        videoArray[0].list.push({
                                            key: f.cover,
                                            name: f.tag,
                                            type: 'image'
                                        })
                                        videoArray[0].list.push({
                                            key: f.video,
                                            name: f.tag,
                                            type: 'video'
                                        })
                                    }
                                })

                                item.value = new Array(Number(item.imageCount) + Number(item.videoCount))
                                item.value.splice(0, imageArray.length, ...imageArray)
                                item.value.splice(Number(item.imageCount), videoArray.length, ...videoArray)
                                console.log('i驾校视频及展示图e', item)
                            } else if (item.key === 'schoolScale') {
                                const arr: { label: string; describe: string }[] = []
                                result.schoolScale.forEach((item: any) => {
                                    arr.push({
                                        label: item.tag,
                                        describe: item.msg
                                    })
                                })

                                item.value = arr
                            } else {
                                item.value = result[item.key as string]
                            }

                            console.log('key', item.key, result[item.key as string], item.value)
                        })
                    }
                })
            }
        })
    }

    //取消创建
    onCancel = () => {
        this.routerStore.removeHeaderRoute(this.routerStore.selectIndex)
        router.push('/driving-school')
    }
    //保存
    onSave = (formRef: any) => {
        console.log('formData', this.formData)
        const data: drivingSchoolOperationInterface = {
            city: '', //所在城市
            developHistory: [], //发展历程
            fullName: '', //全称
            governmentQualification: [], //政府资质
            honor: [], //所获荣誉
            logo: '', //驾校logo
            motto: '', //校训
            passRateInfos: [], //	驾校合格率，注意，这里是2条数据 1条是全市的，1条是驾校合格率
            qualification: '', //资质
            qualificationPic: [], //资质图片
            schoolPic: [], //驾校图片
            shortName: '', //简称
            tag: [], //标签
            details: '', //驾校详情
            schoolScale: [], //规模和说明
            schoolVideo: [], //驾校视频
            customerServiceTel: '',
            customerServiceUrl: '',
            homeLogo: '',
            loginLogo: ''
        }
        const allCityPass: passRateInfosInterface = {
            recordDate: 0, //yyyymm
            subjectFourTotalPassRate: 0, //科目四合格率
            subjectOnePassRate: 0, //	科目一合格率
            subjectThreeTotalPassRate: 0, //科目三合格率
            subjectTwoTotalPassRate: 0, //科目二合格率
            totalPassRate: 0, //综合合格率
            type: 1 //类型(1.全市；2.驾校)
        }
        const drivingSchoolPass: passRateInfosInterface = {
            recordDate: 0, //yyyymm
            dateRank: 0, //排名 类型1的时候不用传或给0
            subjectFourTotalPassRate: 0, //科目四合格率
            subjectOnePassRate: 0, //	科目一合格率
            subjectThreeTotalPassRate: 0, //科目三合格率
            subjectTwoTotalPassRate: 0, //科目二合格率
            totalPassRate: 0, //综合合格率
            type: 2 //类型(1.全市；2.驾校)
        }
        if (this.operation.type === 'edit') {
            allCityPass.id = this.operation.cityPassId
            drivingSchoolPass.id = this.operation.schoolId
        }

        if (formRef?.validateForm()) {
            this.formData.forEach((child: PropsFormpData) => {
                if (Object.prototype.toString.call(child) === '[object Array]') {
                    const childList = child as formDataInterface[]
                    childList.forEach((item: formDataInterface) => {
                        // console.log('item', item)
                        if (item.key === 'logo') {
                            //logo
                            const logo: fileProps[] = item.value as fileProps[]
                            data[item.key] = logo[0].list[0].key
                        } else if (item.key === 'cityId') {
                            //所在城市
                            const arr = item.value as { label: string; id: string }[]
                            data.city = arr[0].label + '/' + arr[1].label
                            data.cityId = arr[0].id + '/' + arr[1].id

                            console.log('cityId', arr, data.city, data.cityId)
                        } else if (item.key === 'introduction') {
                            //驾校介绍说明 0'政府资质',1'发展历程', 2'所获荣誉', 3'驾校详情'
                            const contentArray: string[] = item.content as string[]
                            const describeArray: string[] = item.describe as string[]
                            //政府资质
                            const governmentQualification: describeInterface[] = [
                                {
                                    msg: addDisplayBlockToImages(contentArray[0]),
                                    tag: describeArray[0]
                                }
                            ]
                            data.governmentQualification = governmentQualification
                            //发展历程
                            const developHistory: describeInterface[] = [
                                {
                                    msg: addDisplayBlockToImages(contentArray[1]),
                                    tag: describeArray[1]
                                }
                            ]
                            data.developHistory = developHistory
                            //所获荣誉
                            const honor: describeInterface[] = [
                                {
                                    msg: addDisplayBlockToImages(contentArray[2]),
                                    tag: describeArray[2]
                                }
                            ]
                            data.honor = honor
                            //驾校详情
                            data.details = addDisplayBlockToImages(contentArray[3])
                        } else if (item.key === 'fullName') {
                            //全称
                            data.fullName = item.value as string
                        } else if (item.key === 'motto') {
                            //校训
                            data.motto = item.value as string
                        } else if (item.key === 'qualification') {
                            //资质
                            data.qualification = item.value as string
                        } else if (item.key === 'qualificationPic') {
                            //资质图片
                            const arr: fileProps[] = item.value as fileProps[]
                            const qualificationPic: describeInterface[] = []
                            arr.forEach(item => {
                                item.list.forEach((list: fileListProps) => {
                                    console.log('list', list)
                                    qualificationPic.push({ pic: list.key, tag: list.name })
                                })
                            })
                            console.log('arr', arr)
                            console.log('qualificationPic', qualificationPic)
                            data.qualificationPic = qualificationPic
                        } else if (item.key === 'schoolVideo') {
                            //驾校视频及展示图
                            const arr: fileProps[] = item.value as fileProps[]
                            const schoolPic: describeInterface[] = []
                            const schoolVideo: describeInterface[] = []
                            arr.forEach(item => {
                                if (item.type === 'video') {
                                    let cover = ''
                                    let video = ''
                                    let tag = ''
                                    item.list.forEach((list: fileListProps) => {
                                        console.log('list', list)
                                        if (list?.type === 'video') {
                                            video = list.key
                                            tag = list.name
                                        } else {
                                            cover = list.key
                                        }
                                    })
                                    schoolVideo.push({
                                        cover,
                                        video,
                                        tag
                                    })
                                } else {
                                    item.list.forEach((list: fileListProps) => {
                                        console.log('list', list)
                                        schoolPic.push({ pic: list.key, tag: list.name })
                                    })
                                }
                            })
                            data.schoolPic = schoolPic
                            //驾校视频
                            data.schoolVideo = schoolVideo
                        } else if (item.key === 'shortName') {
                            //简称
                            data.shortName = item.value as string
                        } else if (item.key === 'tag') {
                            //标签
                            data.tag = [...(item.value as string[])]
                        } else if (item.key === 'schoolScale') {
                            //规模和说明
                            const arr: tagProps[] = item.value as tagProps[]
                            const schoolScale: { msg: string; tag: string }[] = []

                            arr.forEach(item => {
                                schoolScale.push({
                                    msg: item.describe,
                                    tag: item.label
                                })
                            })
                            data.schoolScale = schoolScale
                        } else if (item.key === 'month') {
                            allCityPass.recordDate = Number((item.value as string).split('-').join(''))
                            drivingSchoolPass.recordDate = Number((item.value as string).split('-').join(''))
                        } else if (item.key === 'city_totalPassRate') {
                            allCityPass.totalPassRate = Number(item.value)
                        } else if (item.key === 'city_subjectOnePassRate') {
                            allCityPass.subjectOnePassRate = Number(item.value)
                        } else if (item.key === 'city_subjectTwoTotalPassRate') {
                            allCityPass.subjectTwoTotalPassRate = Number(item.value)
                        } else if (item.key === 'city_subjectThreeTotalPassRate') {
                            allCityPass.subjectThreeTotalPassRate = Number(item.value)
                        } else if (item.key === 'city_subjectFourTotalPassRate') {
                            allCityPass.subjectFourTotalPassRate = Number(item.value)
                        } else if (item.key === 'totalPassRate') {
                            drivingSchoolPass.totalPassRate = Number(item.value)
                        } else if (item.key === 'ranking') {
                            drivingSchoolPass.dateRank = Number(item.value)
                        } else if (item.key === 'subjectOnePassRate') {
                            drivingSchoolPass.subjectOnePassRate = Number(item.value)
                        } else if (item.key === 'subjectTwoTotalPassRate') {
                            drivingSchoolPass.subjectTwoTotalPassRate = Number(item.value)
                        } else if (item.key === 'subjectThreeTotalPassRate') {
                            drivingSchoolPass.subjectThreeTotalPassRate = Number(item.value)
                        } else if (item.key === 'subjectFourTotalPassRate') {
                            drivingSchoolPass.subjectFourTotalPassRate = Number(item.value)
                        } else if (item.key === 'customerServiceTel') {
                            data.customerServiceTel = item.value as string
                        } else if (item.key === 'customerServiceUrl') {
                            data.customerServiceUrl = item.value as string
                        } else if (item.key === 'homeLogo') {
                            //logo
                            const logo: fileProps[] = item.value as fileProps[]
                            data[item.key] = logo[0].list[0].key
                        } else if (item.key === 'loginLogo') {
                            const logo: fileProps[] = item.value as fileProps[]
                            data[item.key] = logo[0].list[0].key
                        }
                    })
                }
            })

            data.passRateInfos = [allCityPass, drivingSchoolPass]
            data.styleInfo = JSON.stringify(this.dialog.styleInfo)

            console.log('data', data)
            if (this.operation.type === 'create') {
                drivingSchoolAdd(data).then(res => {
                    if (Number(res.data.code) === 200) {
                        ElMessage.success('新增成功！')
                        this.routerStore.removeHeaderRoute(this.routerStore.selectIndex)
                        router.push('/driving-school')
                        storage.remove('drivingSchoolSimple')
                        this.uStore.updateDrivingSchoolSimple()
                    }
                })
            } else {
                data.id = this.operation.id
                drivingSchoolEdit(data).then(res => {
                    if (Number(res.data.code) === 200) {
                        ElMessage.success('修改成功！')
                        storage.remove('drivingSchoolSimple')
                        this.routerStore.removeHeaderRoute(this.routerStore.selectIndex)
                        router.push('/driving-school')
                        this.uStore.updateDrivingSchoolSimple()
                    }
                })
            }
        }
    }
    onOpenDialog = () => {
        this.dialog.visible = true
    }
    dialogClose = () => {
        this.dialog.visible = false
    }
    dialogConfirm = (res: any) => {
        this.dialog.visible = false
        this.dialog.styleInfo.theme = res.theme
        this.dialog.styleInfo.homeBanner = res.homeBanner
        console.log('confirm', res)
    }
}
